(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define([], factory);
  } else if (typeof exports !== "undefined") {
    factory();
  } else {
    var mod = {
      exports: {}
    };
    factory();
    global.index = mod.exports;
  }
})(this, function () {
  'use strict';

  $(function () {
    // const lately = new Swiper('#lately', {
    //   mousewheel: true,
    //   freeMode: true,
    //   pagination: {
    //     el: '.swiper-pagination',
    //     type: 'progressbar',
    //   },
    // });
    var wallpaper = {
      height: 0,
      isHeight: false
    };
    window.onscroll = function (e) {
      setWallpaperHeight(e.target.scrollingElement.scrollTop);
    };
    /**
     * 
     * @param {Int} scrollTop 距离顶部距离
     */
    function setWallpaperHeight(scrollTop) {
      if (!wallpaper.isHeight) {
        wallpaper.isHeight = $('#app-background').height();
      }
      wallpaper.height = wallpaper.isHeight - scrollTop;
      if (wallpaper.height <= 90) {
        wallpaper.height = 90;
      }
      $('#app-background').height(wallpaper.height);
    }
    // console.log(chrome.history)
    // console.log(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)
    chrome.history.search({
      text: '',
      startTime: new Date('2020-9-28').getTime(),
      endTime: new Date().getTime(),
      maxResults: 100
    }, function (e) {
      var html = '';
      // let elm = '';
      var res = mergeData(e, 'title');
      res.forEach(function (item, i) {
        // if (i < 12) {
        // html += getHtml(item, 'history' + i);
        $('#lately').append(getHtml(item, 'history' + i));
        // if (i % 12 == 11) {
        //   lately.appendSlide('<div class="swiper-slide">' + html + '</div>');
        //   html = ''
        // }
      });
      // $('#lately').append(html);
      // lately.appendSlide(['<div class="swiper-slide">' + html + '</div>', '<div class="swiper-slide">' + html + '</div>']);
    });
    // 当前访问
    chrome.tabs.query({
      title: ''
    }, function (res) {
      var html = '';
      res.forEach(function (item, i) {
        if (item.url != 'chrome://newtab/') {
          getImage(item.favIconUrl).then(function (res) {
            $('#img-current' + i).attr('src', res);
          }).catch(function () {
            $('#img-current' + i).attr('src', '/icon/default-icon.png');
          });
          // html += '<li class="current-tab_item">\
          //         <a href="' + item.url + '">\
          //           <div class="icon"><img id="img-current' + i + '"/></div>\
          //           <p class="title">' + item.title + '</p>\
          //         </a>\
          //         <button class="btn"></button>\
          //       </li>';
          html += '<li class="current-tab_item">\
                <a href="' + item.url + '">\
                  <div class="icon"><img id="img-current' + i + '"/></div>\
                  <p class="title">' + item.title + '</p>\
                </a>\
              </li>';
        }
      });
      $('#current').append(html);
      setTimeout(function () {
        setWallpaperHeight($(window).scrollTop());
      }, 300);
    });

    //获取收藏
    chrome.bookmarks.getTree(function (res) {
      console.log(res);
    });
    var searchHistory = localStorage.getItem('search-history');
    if (searchHistory) {
      searchHistory = searchHistory.split(',');
    } else {
      searchHistory = [];
    }

    $('#search-input').on('input', function (e) {
      // console.log(e.target.value)
    }).on('keyup', function (e) {
      if (e.keyCode === 13) {
        var val = e.target.value;
        if ($.trim(val) != '') {
          if (searchHistory.indexOf(val) == -1) {
            searchHistory.push(val);
            localStorage.setItem('search-history', searchHistory.join(','));
          }
        }
        $(this).val('');
        // window.location.href = 'https://www.baidu.com/s?wd=' + val;
      }
    });
  });
  /**
   * 希尔排序-根据对应值排序
   * @param {Object} d 
   * @param {String} name 
   * @param {String} type desc降序大到小/asc升序小到大
   */
  function sortOrder(d, name, order) {
    var len = d.length,
        temp,
        gap = 1;
    while (gap < len / 5) {
      //动态定义间隔序列
      gap = gap * 5 + 1;
    }
    for (gap; gap > 0; gap = Math.floor(gap / 5)) {
      for (var i = gap; i < len; i++) {
        temp = d[i];
        for (var j = i - gap; j >= 0 && orderCompare(d[j][name], temp[name], order, name); j -= gap) {
          d[j + gap] = d[j];
        }
        d[j + gap] = temp;
      }
    }
    return d;
  }

  function orderCompare(p1, p2, type, name) {
    var res = null;
    if (isNaN(parseInt(p1)) || isNaN(parseInt(p2))) {
      res = type == 'asc' ? p1 > p2 : p1 < p2;
    } else {
      res = type == 'asc' ? parseInt(p1) > parseInt(p2) : parseInt(p1) < parseInt(p2);
    }
    return res;
  }
  /**
   * 格式化日期
   * @param {Date} date 
   */
  function formatTime(date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  }

  function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  }
  /**
   * 获取图片
   * @param {String} url 
   */
  function getImage(url) {
    return new Promise(function (resolve, reject) {
      var img = new Image();
      // img.crossOrigin = 'Anonymous';
      img.src = url; //背景图片
      img.onload = function (e) {
        resolve(url);
      };
      img.onerror = function () {
        reject(false);
      };
    });
  }

  function getHtml(e, id) {
    var str = e.url.split('/');
    var url = str[2];
    var icon = str[0] + '//' + url + '/favicon.ico';
    var date = formatTime(new Date(e.lastVisitTime));
    getImage(icon).then(function (res) {
      $('#img-' + id).attr('src', res);
    }).catch(function () {
      $('#img-' + id).attr('src', '/images/default-icon.png');
    });
    if (!e.title) {
      if (e.url.indexOf('http://') > -1) {
        e.title = e.url.split('http://')[1];
      } else if (e.url.indexOf('https://') > -1) {
        e.title = e.url.split('https://')[1];
      }
    }
    var ift_col = $('<div>', {
      class: 'ift-col'
    });
    var app_container_item = $('<a>', {
      class: 'app-container_item',
      href: e.url
    });
    var app_container_icon = $('<div>', {
      class: 'app-container_icon'
    }).append('<img id="img-' + id + '" onerror="onIconError"/>');

    var app_container_info = $('<div>', {
      class: 'app-container_info'
    });
    var title = $('<p>', {
      class: 'app-container_name',
      html: e.title
    });
    var bottom = $('<div>', {
      class: 'bottom'
    }).append('<span>' + date + '  ' + e.visitCount + '</span>').append($('<span>', {
      class: 'url',
      html: url
    }));
    app_container_info.append(title).append(bottom);
    app_container_item.append(app_container_icon);
    app_container_item.append(app_container_info);
    ift_col.append(app_container_item);
    return ift_col;
  }
  //合并相同数据
  function mergeData(data, type) {
    var hash = [],
        arr = [];
    data.map(function (item) {
      if (hash.indexOf(item[type]) == -1) {
        hash.push(item[type]);
        arr.push(item);
      }
    });
    return arr;
  }
});